package cn.dgut.jy.soro.service.impl;

import cn.dgut.jy.soro.entity.Verification;
import cn.dgut.jy.soro.repository.VerificationRepository;
import cn.dgut.jy.soro.service.VerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class VerificationServiceImpl implements VerificationService {
    private VerificationRepository verificationRepository;

    @Autowired
    public VerificationServiceImpl(VerificationRepository verificationRepository) {
        this.verificationRepository = verificationRepository;
    }

    @Override
    public String createVerificationAndSave(String email) {
        String verification = String.valueOf(new Random().nextInt(899999) + 100000);
        Verification v;
        if(verificationRepository.findByEmail(email) == null) {
            v = new Verification();
            v.setEmail(email);
            v.setVerification(verification);
        } else {
            v = verificationRepository.findByEmail(email);
            v.setVerification(verification);
        }

        verificationRepository.save(v);
        return verification;
    }

    @Override
    public Boolean verifying(String email, String verification) {
        Verification v = verificationRepository.findByEmail(email);
        return v != null && v.getVerification().equals(verification);
    }
}
